<template>
  <div id="app" style="overflow: hidden;width:100%;height:100%;">
    <vxe-grid ref="xGrid" v-bind="grid_options" :row-config="{height:36}" @form-reset="formResetEvent">
    </vxe-grid>
    <defectTask ref="defectTask" @closeEvent="closeEvent"></defectTask>
    <auditEquipment ref="auditEquipment" @closeShEvent="closeShEvent"></auditEquipment>
  </div>


</template>

<script>
import {reactive} from 'vue'
import {GridEvent} from './model/defectTaskTable.js'
import defectTask from './components/defectTask.vue'
import auditEquipment from './components/auditEquipment.vue'
import {defectTaskApi} from "@/api/defects/defectTaskApi";
import util from '@/utils/util'
import {Message, MessageBox} from 'element-ui';
import VXETable from "vxe-table";
import {getInfo} from "@/api/login";
import {listDept} from "@/api/system/dept";

export default {
  name: 'defectTaskIndex',
  components: {defectTask, auditEquipment},
  props: {
    row: {
      type: Object,
    },
    formData: {
      type: Object,
    },
  },
  data() {
    return {
      LanderId: "",
      dwinfo: '',
      GridEvent: reactive(GridEvent),
      grid_options: {
        border: true,
        stripe: true,
        showHeaderOverflow: true,
        showOverflow: true,
        keepSource: true,
        id: 'full_edit_1',
        height: 700,
        rowId: 'id',  //指定记录主键
        rowConfig: {
          isHover: true
        },
        columnConfig: {
          resizable: true
        },
        customConfig: {
          storage: true,
        },
        sortConfig: {
          trigger: 'cell',
          remote: true
        },
        filterConfig: {
          remote: true
        },
        formConfig: {
          form: true, // 启用表单代理
          size: "medium",        //尺寸
          titleAlign: "right",  //所有项的标题对齐方式
          titleWidth: "120", //标题宽度
          titleColon: true,     //是否显示标题冒号
          collapseStatus: false,   //折叠状�?�aa//
          items: [
            {
              field: 'xqdwbm',
              title: '单位:',
              span: 6,
              itemRender: {name: '$select', options: [], props: {placeholder: '---请选择设备状态---'}},
            },
            {
              field: 'gdmc',
              title: '工单名称:',
              span: 6,
              itemRender: {name: '$input', props: {placeholder: '---请输入---'}},
            },
            {
              field: 'jhkssj',
              title: '消缺时间',
              span: 6,
              itemRender: {name: '$input', props: {type: 'datetime', placeholder: '年/月/日'}}
            },
            {
              field: 'jhkssj_to',
              title: '至',
              span: 6,
              itemRender: {name: '$input', props: {type: 'datetime', placeholder: '年/月/日'}},
              folding: true,
            },
            {
              field: 'gdzt',
              title: '工单状态:',
              span: 6,
              folding: true,
              itemRender: {name: '$select', options: [], props: {placeholder: '---请选择设备状态---'}},
            },
            {
              span: 6, collapseNode: true, align: 'right', itemRender: {
                name: '$buttons', children: [
                  {props: {type: 'submit', content: '查询', status: 'primary', icon: 'fa fa-search'}},
                  {props: {type: 'reset', content: '重置', icon: 'fa fa-reply'}},
                ]
              }
            }
          ]
        },
        toolbarConfig: {
          buttons: [
            {buttonRender: {name: 'add', events: {click: this.addRowModal}}}, // 新增
            {buttonRender: {name: 'edit', events: {click: this.editRowModal}}},//编辑
            {buttonRender: {name: 'delete', events: {click: this.handleDelete}}},//删除
          ],
          refresh: true,
          custom: true,
        },
        pagerConfig: {
          pageSize: 10,
          pageSizes: [5, 10, 15, 20, 50, 100],
          layouts: ['PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total'],
          background: true,
        },
        proxyConfig: {
          seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
          sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
          filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
          form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
          // 对应响应结果 { result: [], page: { total: 100 } }
          props: {
            result: 'data.records', // 配置响应结果列表字段
            total: 'data.total' // 配置响应结果总页数字段
          },
          // 只接收Promise，具体实现自由发挥
          ajax: {
            // 当点击工具栏查询按钮或者手动提交指令 query或reload 时会被触发
            query: async ({page, sorts, filters, form}) => {
              // =====给表单项赋初始值======
              await this.initFormData(form);
              //    this.enableDefault = false;
              const queryParams = Object.assign({}, form)
              // const queryParams = this.initFormData(form)
              // 处理排序条件
              const firstSort = sorts[0]
              if (firstSort) {
                queryParams.sort = firstSort.property
                queryParams.order = firstSort.order
              }
              // 处理筛选条件

              filters.forEach(({property, values}) => {
                queryParams[property] = values.join(',')
              })
              return this.queryData(page, queryParams)
            },
          }
        },
        columns: [
          {type: 'seq', title: '序号', width: "60px", align: 'center', headerAlign: 'center'},
          {type: 'checkbox', width: "60px", align: 'center', headerAlign: 'center', visible: true},
          {field: 'xqdwmc', title: '单位', minWidth: "120px", align: 'center', headerAlign: 'center'},
          {
            field: 'gdmc',
            title: '消缺工单名称',
            minWidth: "160px",
            align: 'center',
            headerAlign: 'center',
            cellRender: {name: 'gdmc', events: {click: this.workOrderModel}}
          },
          {field: 'pdrTel', title: '派单人电话', minWidth: "160px", align: 'center', headerAlign: 'center',},
          // { field: 'xqbzmc', title: '消缺班组', minWidth: "160px", align: 'center', headerAlign: 'center', },
          {field: 'jhkssj', title: '计划开始时间', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {field: 'jhjssj', title: '计划结束时间', minWidth: "160px", align: 'center', headerAlign: 'center'},
          {field: 'xqnr', title: '消缺主要内容', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {field: 'gdztMc', title: '工单状态', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {field: 'createPersonName', title: '创建人', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {field: 'createTime', title: '创建时间', minWidth: "160px", align: 'center', headerAlign: 'center',},
          // { field: 'shyj', title: '审核意见', minWidth: "100px", align: 'center', headerAlign: 'center', },
        ],
        checkboxConfig: {
          // labelField: 'id',
          reserve: true,
          highlight: true,
          range: true
        },
        editConfig: {
          trigger: 'click',
          mode: 'row',
          showStatus: true
        }
      },
      djztOptions: [],
      rowDjshzt: false,
      enableDefault: true
      //  api: 'fetchQueryQueryRwxqByPage',
      // init: true
    }
  },
  computed: {
    options() {
      return {
        djztOptions: this.djztOptions,
        kfOptions: this.kfOptions
      }
    }
  },
  created() {
    // this.setReadModel()


  },
  mounted() {

    this.$nextTick(function () {
      this.getKfOptions()
      this.getOptionData_gldw()
      GridEvent.getOptionData_taskNo(this.$refs.xGrid)
    })
    window.addEventListener('resize', this.setTableHeight);
  },
  destroyed: function () {
    window.removeEventListener('resize', this.setTableHeight);
  },
  methods: {
    timeformat(dat, value, type) {
      let year = dat.getFullYear();
      let mon = (dat.getMonth() + 1) < 10 ? "0" + (dat.getMonth() + 1) : dat.getMonth() + 1;
      let data = dat.getDate() < 10 ? "0" + (dat.getDate() - value) : dat.getDate() + value;
      if (type === 'start') {
        var newDate = year + "-" + mon + "-" + data + " " + '00' + ":" + '00' + ":" + '00';
      } else {
        var newDate = year + "-" + mon + "-" + data + " " + '23' + ":" + '59' + ":" + '59';
      }
      return newDate;
    },
    formResetEvent({data}) { // 重置表单
      let datatime = new Date()
      data['jhkssj'] = this.timeformat(datatime, 0, 'start')
      data['jhkssj_to'] = this.timeformat(datatime, 0, 'end')
      data['gdzt'] = '0'
    },
    getOptionData_gldw() {
      getInfo().then(res => {
        this.LanderId = res.user.userId
        let params = {
          deptId: res.user.dept.deptId,
          parentId: res.user.dept.parentId
        }
        listDept(params).then(result => {
          this.dwinfo = result.data
          let optionList = [
            {label: '请选择', value: ''}
          ]
          result.data.forEach((item) => {
            optionList.push({label: item.deptName, value: item.deptId})

          })
          const item = this.$refs.xGrid.getFormItems(0)
          item.itemRender.options = optionList
        })
      })
    },
    handChange(val) {
      let dw = []
      dw = this.dwinfo.filter((item) => {
        return item.organid == val.data.xqdwbm
      })
      let params = {
        deptId: '',
        parentId: dw[0].organid
      }
      listDept(params).then((res) => {
        let optionList = [
          {label: '请选择', value: ''}
        ]
        res.data.forEach((item) => {
          optionList.push({label: item.deptName, value: item.deptId})

        })
        const item = this.$refs.xGrid.getFormItems(1)
        item.itemRender.options = optionList
      })
    },
    // 高度自适应
    setTableHeight: function () {
      const tableContainer = document.querySelector("#app");
      const height = tableContainer.clientHeight;
      this.grid_options.height = height - 5;
    },
    //查询控制
    setReadModel() { //控制是否显示
      const isRead = util.isReadModel()
      if (isRead) {
        // this.grid_options.toolbarConfig.buttons=[{ buttonRender: { name: 'auditpass', events: { click: this.handleAuditPass } } }]
        this.grid_options.toolbarConfig.buttons = []
        this.grid_options.columns[1].visible = false
      }
    },
    initFormData(form) {
      const that = this;
      let datatime = new Date()
      if (that.enableDefault) {
        // 查询框默认值初识化
        if (this.row !== undefined) {
          form.jhkssj = this.formData.jhkssj
          form.jhkssj_to = this.formData.endTime
        } else {
          form.gdzt = '0'
          form.jhkssj = this.timeformat(datatime, 0, 'start')
          form.jhkssj_to = this.timeformat(datatime, 0, 'end')
        }
        this.enableDefault = false;
      }
    },
    getKfOptions() {
      // warehouseManagement.getKfList().then(res => {
      //   let optionList = [
      //     { label: '请选择', value: '' }
      //   ]
      //   res.data.forEach((item)=>{
      //     optionList.push({label: item.kfName, value: item.id})
      //   })
      //   this.kfOptions = optionList
      //   const item = this.$refs.xGrid.getFormItems(4)
      //   item.itemRender.options = optionList
      // })
    },
    queryData: (page, formData) => {
      const queryParams = {
        pageSize: page.pageSize,
        pageNo: page.currentPage,
        entity: {
          xqdwbm: formData.xqdwbm ? formData.xqdwbm : null,
          gdmc: formData.gdmc ? formData.gdmc : null,
          gdzt: formData.gdzt ? formData.gdzt : null,
          gdResousId: formData.gdResousId ? formData.gdResousId : null,
          xqbzbm: formData.xqbzbm ? formData.xqbzbm : null,
          jhkssj: formData.jhkssj ? formData.jhkssj : null,
          jhkssj_to: formData.jhkssj_to ? formData.jhkssj_to : null
        },
        paramsMap: {},
        column: '',
        order: ''
      }

      return defectTaskApi.page(queryParams)
      // console.log(defectTaskApi.page(queryParams))
      //  defectTaskApi.page(queryParams).then((result) =>{
      //  result.data.records.sort((a,b) =>a.createTime-b.createTime); // 降序
      //  console.log(result)
      //  return result

      //  })
    },


    addRowModal() {
      this.$refs.defectTask.showDialog(false)
    },
    editRowModal() {
      const rowArr = this.$refs.xGrid.getCheckboxRecords(true);

      if (rowArr && rowArr.length === 1) {
        if (rowArr[0].gdztMc == '已派单') {
          this.$message.warning("已派单不支持修改")
        } else {
          this.$refs.defectTask.showDialog(true, rowArr[0])
        }
      } else {
        // VXETable.modal.confirm({content: '有且只能够操作一条记录\n请选择一条记录', title: '操作异常', status: 'error'})
        this.$message.warning("至少选中1行数据")
      }
    },
    handleDelete() {
      const rowsArr = this.$refs.xGrid.getCheckboxRecords(true);
      if (rowsArr && rowsArr.length >= 1) {
        if (rowsArr[0].gdztMc == '已派单') {
          this.$message.warning("已派单不支持删除")
        } else {
          rowsArr.forEach((item) => {
            if (item.createPerson != this.LanderId) {
              MessageBox.confirm('此删除包括非当前登陆人创建工单, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                let queryParams = []
                rowsArr.forEach(item => {
                  queryParams.push(item.id)
                })

                //删除数据后台如何处理，按照实际的�? 处理多行记录信息rows//
                defectTaskApi.delete(queryParams).then(res => {
                  //删除成功后，会掉表格刷新//
                  this.$refs.xGrid.commitProxy('query')
                  Message({
                    type: 'success',
                    message: '删除成功!'
                  });
                }).catch(err => {
                  console.error(err)
                })
              }).catch(() => {
                Message({
                  type: 'info',
                  message: '已取消删!'
                });
              });
            } else {
              MessageBox.confirm('此操作将永久删除, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                let queryParams = []
                rowsArr.forEach(item => {
                  queryParams.push(item.id)
                })

                //删除数据后台如何处理，按照实际的�? 处理多行记录信息rows//
                defectTaskApi.delete(queryParams).then(res => {
                  //删除成功后，会掉表格刷新//
                  this.$refs.xGrid.commitProxy('query')
                  Message({
                    type: 'success',
                    message: '删除成功!'
                  });
                }).catch(err => {
                  console.error(err)
                })
              }).catch(() => {
                Message({
                  type: 'info',
                  message: '已取消删!'
                });
              });
            }
          })

        }

      } else {
        this.$message.warning("至少选中1行数据")
      }


    },
    handleAuditall() { //批量提交审核的方法
      const rowsArr = this.$refs.xGrid.getCheckboxRecords(true);
      const rowscheck = []
      var isAudit = true
      rowsArr.map(item => {
        if (item.djshzt !== '0') {
          isAudit = false
          return isAudit
        } else {
          rowscheck.push(item.id)
        }
      })
      if (isAudit) {
        let queryParams = rowscheck
        defectTaskApi.submitShByIds(queryParams).then(res => {
          if (res.code === '200') {
            this.$message.success(res.message)
            this.$refs.xGrid.commitProxy('query')
          }
        })
      } else {
        VXETable.modal.confirm({
          content: '包含不可进行提交审核操作数据\n请重新选择记录',
          title: '操作异常',
          status: 'error'
        })
      }
    },
    handleAudit(row) { //提交审核的方法
      const isRead = util.isReadModel()
      if (isRead) {
        this.$refs.auditEquipment.showDialog(true, row.row)
      } else {
        const rowcheck = []
        rowcheck.push(row.row.id)
        let queryParams = rowcheck
        defectTaskApi.submitShByIds(queryParams).then(res => {
          if (res.code === '200') {
            this.$message.success(res.message)
            this.$refs.xGrid.commitProxy('query')
          }
        })
      }
    },
    workOrderModel(row) {
      this.$refs.defectTask.showDialog(true, row.row, 1)
    },
    closeEvent() {
      this.$refs.xGrid.commitProxy('query')
    },
    closeShEvent() {
      this.$refs.xGrid.commitProxy('query')
    }
  }
}
// 创建一个简单的工具栏-左侧按钮渲染
VXETable.renderer.add('add', {
  renderToolbarButton(h, renderOpts, params) {
    const {events = {}} = renderOpts
    const {button, $table} = params
    return [
      <vxe-button icon="fa fa-plus (alias)" content="新增" onClick={
        () => {
          events.click(button)
        }
      }></vxe-button>
    ]
  }
})

// 创建一个简单的工具栏-左侧按钮渲染
VXETable.renderer.add('edit', {
  renderToolbarButton(h, renderOpts, params) {
    const {events = {}} = renderOpts
    const {button, $table} = params
    return [
      <vxe-button icon="fa fa-edit (alias)" content="修改" onClick={
        () => {
          events.click(button)
        }
      }></vxe-button>
    ]
  }
})
// 创建一个简单的工具栏-左侧按钮渲染
VXETable.renderer.add('delete', {
  renderToolbarButton(h, renderOpts, params) {
    const {events = {}} = renderOpts
    const {button, $table} = params
    return [
      <vxe-button icon="fa fa-times (alias)" content="删除" onClick={
        () => {
          events.click(button)
        }
      }></vxe-button>
    ]
  }
})
// 消缺工单名称穿透
VXETable.renderer.add('gdmc', {
  renderDefault(h, renderOpts, params) {
    let {row, column} = params
    let {events} = renderOpts
    return [
      <a style="color:#0000FF;cursor: pointer; " onClick={() => events.click(params)}>{row.gdmc}</a>
    ]
  }
})
</script>

<style scoped>

</style>
